<?php
/**
 * Created by PhpStorm.
 * User: HP
 * Date: 2018/5/8
 * Time: 16:40
 */

namespace app\user;

use app\common\Common;
use app\data\UserData;
use app\pay\WeChatPay;
use messenger\Messenger;
use think\Db;
use wechat\WeChat;

class User extends Base
{

    /**
     * 用户名字长度限制
     * @var array
     */
    private $userName = [2, 10];


    /**
     * 排序方法
     * @var array
     */
    private $sortType = ['desc', 'asc'];

    /**
     * 原始会员排序
     * @var array
     */
    private $sortOriginal = ['create_time'];


    /**
     * 原始会员排序
     * @var array
     */
    private $sortFriend = ['create_time'];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 申请创始会员
     * @param $user_id
     * @param $user_name
     * @param $card_number
     * @param $img_positive
     * @param $img_back
     * @return \think\response\Json
     */
    public function addOriginalMember($user_id, $user_name, $card_number, $img_positive, $img_back)
    {

        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        if (!Common::validateIdCard($card_number)) {
            return json(['code' => $this->f_code, 'msg' => '身份证号码错误']);
        }
        $len = strlen($user_name);
        if ($len < $this->userName[0] || $len > $this->userName[1]) {
            return json(['code' => $this->f_code, 'msg' => '请输入正确的姓名']);
        }
        $user = new UserData();
        $time = time();
        $bool_positive = preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $img_positive);
        $bool_back = preg_match('/.*(\.png|\.jpg|\.jpeg|\.gif)$/', $img_back);
        if ($bool_positive != 1 && $bool_back != 1) {
            return json(['code' => $this->f_code, 'msg' => '图片格式错误']);
        }
        if (strlen($img_positive) > 200 || strlen($img_back) > 200) {
            return json(['code' => $this->f_code, 'msg' => '图片长度过长']);
        }
        $res = $user->addOriginalMember($user_id, $user_name, $card_number, $time, $img_positive, $img_back);
        return is_numeric($res) ? json([
            'code' => $this->f_code, 'msg' => '申请失败请稍后重试'
        ]) : json([
            'code' => $this->t_code, 'msg' => '申请成功'
        ]);
    }

    /**
     * 显示
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @param int $status
     * @param int $recover
     * @return \think\response\Json
     */
    public function showOriginalMember($page = 1, $pre = 15, $sort = ['create_time' => 'desc'], $status = 0, $recover = 0)
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->sortOriginal, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $where = 'recover_status = ' . $recover;
        switch ($status) {
            case 1:
                $where .= ' and verify_status=0';
                break;
            case 2:
                $where .= ' and verify_status=1';
                break;
            case 3:
                $where .= ' and verify_status=2';
                break;
            default:
                break;
        }
        $user = new UserData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $user->showOriginalMember($page, $pre, $sort, $where),
                'total' => $user->total($where, 'drh_original_member')
            ]
        ]);
    }

    /**
     * 后台审核
     * @param $id
     * @param $user_id
     * @param $status
     * @param string $msg
     * @param string $additional_mgs
     * @return \think\response\Json
     */
    public function reviewOperating($id, $user_id, $status, $msg = 'OK', $additional_mgs = '审核通过')
    {
        $id = Common::getTableValue('drh_original_member', 'id', ['id', 'user_id'], [$id, $user_id]);
        if (empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '不存在申请']);
        }
        if ($status != 1 && $status != 2) {
            return json(['code' => $this->f_code, 'msg' => '状态错误']);
        }
        $user = new UserData();
        $time = time();
        Db::startTrans();
        $res = $user->reviewOperating($id, $user_id, $status);
        $return = Common::addMsg($user_id, 0, $time, $msg, $additional_mgs);
        if ($res != 1 || !is_numeric($return)) {
            Db::rollback();
            return json(['code' => $this->f_code, 'msg' => '数据错误']);
        }
        Db::commit();
        return json(['code' => $this->t_code, 'msg' => '审核成功']);
    }

//    /**
//     *计算某个经纬度的周围某段距离的正方形的四个点
//     *
//     * @param lng float 经度
//     * @param lat float 纬度
//     * @param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
//     * @return array 正方形的四个点的经纬度坐标
//     */
//    public function returnSquarePoint($lng, $lat, $distance = 0.5)
//    {
//        define('EARTH_RADIUS', 6371);//地球半径，平均半径为6371km
//        $d_lng = 2 * asin(sin($distance / (2 * EARTH_RADIUS)) / cos(deg2rad($lat)));
//        $d_lng = rad2deg($d_lng);
//
//        $d_lat = $distance / EARTH_RADIUS;
//        $d_lat = rad2deg($d_lat);
//
//        return array(
//            'left-top' => array('lat' => $lat + $d_lat, 'lng' => $lng - $d_lng),
//            'right-top' => array('lat' => $lat + $d_lat, 'lng' => $lng + $d_lng),
//            'left-bottom' => array('lat' => $lat - $d_lat, 'lng' => $lng - $d_lng),
//            'right-bottom' => array('lat' => $lat - $d_lat, 'lng' => $lng + $d_lng)
//        );
//    }
//
//    public function getDistance($lng1, $lat1, $lng2, $lat2)
//    {//根据经纬度计算距离 单位为公里
////将角度转为狐度
//        $radLat1 = deg2rad($lat1);
//        $radLat2 = deg2rad($lat2);
//        $radLng1 = deg2rad($lng1);
//        $radLng2 = deg2rad($lng2);
//        $a = $radLat1 - $radLat2;//两纬度之差,纬度<90
//        $b = $radLng1 - $radLng2;//两经度之差纬度<180//6378.137
//        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
//        return $s;
//    }
//
//    /**
//     * @param lng float 经度
//     * @param lat float 纬度
//     */
//    function test($lng = '104.2407917976', $lat = '30.5668523045')
//    {
//        $squares = $this->returnSquarePoint($lng, $lat, 5);
//        dump($squares);
//        dump($this->getDistances());
//        exit;
////        30.5668523045  104.2407917976   30.611818384796  104.18856859119
//        $condition = "location_x<>0
//        and
//        location_x>{$squares['right-bottom']['lat']}
//        and
//        location_x<{$squares['left-top']['lat']}
//        and
//        location_y>{$squares['left-top']['lng']}
//        and
//        location_y<{$squares['right-bottom']['lng']}";
//    }
//
//    public function getDistances($lat1='30.5668523045', $lng1='104.2407917976', $lat2='30.611818384796', $lng2='104.18856859119')
//    {
//        $earthRadius = 6367000; //approximate radius of earth in meters
//        $lat1 = ($lat1 * pi()) / 180;
//        $lng1 = ($lng1 * pi()) / 180;
//        $lat2 = ($lat2 * pi()) / 180;
//        $lng2 = ($lng2 * pi()) / 180;
//        $calcLongitude = $lng2 - $lng1;
//        $calcLatitude = $lat2 - $lat1;
//        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
//        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
//        $calculatedDistance = $earthRadius * $stepTwo;
//        return round($calculatedDistance);
//    }

    /**
     * 添加好友
     * @param $user_id
     * @param $friend_id
     * @param $type
     * @return \think\response\Json
     */
    public function addFriend($user_id, $friend_id, $type)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        if (Common::checkTableFields('drh_user_info', 'id', $friend_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        if ($type != 0 && $type != 1 && $type != 2) {
            return json(['code' => $this->f_code, 'msg' => '好友来源错误']);
        }

        if ($user_id == $friend_id) {
            return json(['code' => $this->f_code, 'msg' => '不能添加自己为好友']);
        }
        $id = Common::getTableValue('drh_user_friend', 'friend_id', ['friend_id', 'user_id'], [$friend_id, $user_id]);
        if (!empty($id)) {//存在好友
            return json(['code' => $this->f_code, 'msg' => '好友以存在 请勿重复添加']);
        }
        $id = Common::getTableValue('drh_user_friend', 'friend_id', ['friend_id'], [$friend_id]);
        if (!empty($id)) {//存在好友
            return json(['code' => $this->f_code, 'msg' => '该好友已有上级']);
        }
        $user = new UserData();
        $time = time();
        $id = $user->addFriend($user_id, $friend_id, $time, $type);
        if ($id) {
            return json(['code' => $this->t_code, 'msg' => '添加成功']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '添加失败 请稍后重试!']);
        }
    }

    /**
     * 好友显示
     * @param $user_id
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showFriend($user_id, $page = 1, $pre = 5, $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }

        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->sortFriend, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }

        $user = new UserData();
        $data = $user->showFriend($user_id, $page, $pre, $sort);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data,
                'total' => $user->total("user_id={$user_id}", 'drh_user_friend')
            ]
        ]);
    }

    /**
     * 获取验证码
     * @return string
     */
    public function createVerificationCode()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        session($ip, null);
        $num1 = rand(0, 9);
        $num2 = rand(0, 9);
        session($ip, $num1 + $num2);
        return $num1 . '+' . $num2;
    }


    /**
     * 发送短信
     * @param string $mobile
     * @param string $user_id
     * @param string $sum
     * @return \think\response\Json
     */
    public function sendMsg($mobile = '18380157185', $user_id, $sum)
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        $num_sum = session($ip);
        session($ip, null);
        if ($sum != $num_sum) {
            return json(['code' => $this->t_code, 'msg' => '验证码错误!']);
        }
        $msg = new Messenger();
        if (!Common::checkTel($mobile)) {
            return json(['code' => $this->t_code, 'msg' => '手机号码不正确!']);
        }
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        $con = $msg->sendMsg($mobile);
        $time = time();
        if ($con['code'] == '0') {//发送成功
            if (empty(session($mobile))) {
                $num = 0;
                $old_time = $time;
            } else {
                $data = implode('-', session($mobile));
                $num = $data[0];
                $old_time = $data[1];
            }
            $old = date('Y-m-d', $old_time);
            $new = date('Y-m-d', $time);
            if ($new > $old) {//次日次数清0
                $num = 0;
            } else {
                if ($num >= 6) {
                    return json(['code' => $this->t_code, 'msg' => '请求验证码次数过多请明天在尝试!']);
                }
            }
            $num++;
            session($con['data'], $mobile);
            session($mobile, $num . '-' . $time . '-' . $user_id);
            return json(['code' => $this->t_code, 'msg' => '发送成功']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '发送失败']);
        }
    }

//    /**
//     * 绑定手机号
//     * @param $user_open_id
//     * @param $mobile
//     * @param $verify
//     * @return \think\response\Json
//     */
//    public function bindingTel($user_open_id, $mobile, $verify)
//    {
//        if (!Common::checkTel($mobile)) {
//            return json(['code' => $this->t_code, 'msg' => '手机号码不正确!']);
//        }
//        if (Common::checkTableFields('drh_user_info', 'user_open_id', $user_open_id) == $this->f_code) {
//            return json(['code' => $this->f_code, 'msg' => '不存在该用户']);
//        }
//        $data = implode('-', session($mobile));
//        $old_time = $data[1];
//        $id = $data[2];
//        $verify_tel = session($verify);
//        if ($verify_tel != $mobile || $user_id != $id) {
//            return json(['code' => $this->t_code, 'msg' => '验证码错误!']);
//        }
//        $time = time();
//        if ($time - $old_time > 5 * 60) {
//            return json(['code' => $this->t_code, 'msg' => '验证码以过期!']);
//        }
//        session($verify, null);
//        session($mobile, null);
//        $user = new UserData();
//        if ($user->bindingTel($user_id, $mobile)) {
//            return json(['code' => $this->t_code, 'msg' => '绑定成功']);
//        } else {
//            return json(['code' => $this->t_code, 'msg' => '绑定失败请稍后在试!']);
//        }
//    }


    /**
     * 微信绑定手机号
     * @param $data
     * @param $vi
     * @param $sessionKey
     * @param $user_open_id
     * @return array|\think\response\Json
     */
    public function bindingTel($data, $vi, $sessionKey, $user_open_id)
    {
        if (Common::checkTableFields('drh_user_info', 'user_open_id', $user_open_id) == $this->f_code) {
            return ['code' => $this->f_code, 'msg' => '不存在该用户'];
        }
        $WeChat = new WeChat();
        $res = $WeChat->decrypt($sessionKey, $data, $vi);
        $res = json_decode($res, true);
        if (empty($res['phoneNumber'])) {
            return json(['code' => $this->f_code, 'msg' => '数据错误', 'data' => $res]);
        }
        $tel = $res['phoneNumber'];
        $user = new UserData();
        $data = $user->WXUserTelBind($user_open_id, $tel);
        if (!$data) {
            return json(['code' => $this->f_code, 'msg' => '数据错误请稍后再试']);
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => '手机号绑定成功!'
        ]);
    }

////////////////////////////////------------------新增功能-----------------------////////////////////////////
    /**
     * 关注店铺
     * @param $user_id
     * @param $shop_id
     * @param $status
     * @return \think\response\Json
     */
    public function attentionShop($user_id, $shop_id, $status)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        if (!in_array($status, [0, 1])) {
            return json(['code' => $this->f_code, 'msg' => '操作错误！']);
        }
        $user = new UserData();
        $id = Common::getTableValue('drh_user_attention_shop', ['recover_status', 'id'], ['shop_id', 'user_id'], [$shop_id, $user_id]);
        if (!empty($id)) {
            $user->attentionShopCancel($user_id, $shop_id, $status);
            return json(['code' => $this->t_code, 'msg' => '操作成功！']);
        }
        $time = time();

        $res = $user->attentionShop($user_id, $shop_id, $time);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '关注成功!']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '服务器繁忙请稍后在试!']);
        }
    }


    /**
     * 收藏商品
     * @param $user_id
     * @param $goods_id
     * @param $status
     * @return \think\response\Json
     */
    public function attentionGoods($user_id, $goods_id, $status)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        if (Common::checkTableFields('drh_goods', 'id', $goods_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商品不存在']);
        }
        if (!in_array($status, [0, 1])) {
            return json(['code' => $this->f_code, 'msg' => '操作错误！']);
        }
        $user = new UserData();
        $id = Common::getTableValue('drh_user_attention_goods', ['recover_status', 'id'], ['goods_id', 'user_id'], [$goods_id, $user_id]);
        if (!empty($id)) {
            $user->attentionGoodsCancel($user_id, $goods_id, $status);
            return json(['code' => $this->t_code, 'msg' => '操作成功！']);
        }
        $time = time();

        $res = $user->attentionGoods($user_id, $goods_id, $time);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '收藏成功!']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '服务器繁忙请稍后在试!']);
        }
    }

    /**
     * 评论商品
     * @param $user_id
     * @param $order_num
     * @param string $img
     * @param $msg
     * @param $integral
     * @return \think\response\Json
     */
    public function userCommentOrder($user_id, $order_num, $img = '', $msg, $integral)
    {
        $res = Common::getTableValue('drh_goods_order', ['shop_id', 'goods_status'], ['order_num', 'user_id'], [$order_num, $user_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '不存在该订单']);
        }
        if ($res['goods_status'] != 2) {
            return json(['code' => $this->f_code, 'msg' => '收货后才能评价']);
        }
        $shop_id = $res['shop_id'];
        $res = Common::getTableValue('drh_user_comment', 'id', ['order_num', 'user_id', 'shop_id'], [$order_num, $user_id, $shop_id]);
        if (!empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '请勿重复提交']);
        }
        $time = time();
        if (!empty($img)) {
            if (count($img) > 5) {
                return json(['code' => $this->f_code, 'msg' => '图片不能大于5张']);
            }
            $img = json_encode($img);
        }
        if (mb_strlen($msg) > 5000) {
            return json(['code' => $this->f_code, 'msg' => '评论字数请少于5000字']);
        }
        if ($integral > 100 || $integral < 0) {
            return json(['code' => $this->f_code, 'msg' => '评分不正确']);
        }
        $user = new UserData();
        $res = $user->userCommentOrder($user_id, $order_num, $img, $msg, $integral, $time, $shop_id);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '评论成功!']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '服务器繁忙请稍后在试!']);
        }
    }

    /**
     * @param $user_id
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showCollectionGoods($user_id, $page = 1, $pre = 15, array $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->sortFriend, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $user = new UserData();
        $where = " a.user_id={$user_id} and a.recover_status =1";
        $data = $user->showCollectionGoods($where, $page, $pre, $sort);
        foreach ($data as $k=>$v){
            $data[$k]['goods_attr_value'] = json_decode($v['goods_attr_value'])??unserialize($v['goods_attr_value']);
            $data[$k]['goods_img'] = json_decode($v['goods_img'])??unserialize($v['goods_img']);
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data,
                'total' => Common::total($where, "drh_user_attention_goods a")
            ]
        ]);
    }

    private function getImage($data)
    {
        foreach ($data as $k => $v) {
            $goods_img = json_decode($v['goods_img']);
            $goods_img = empty($goods_img[0]) ? '' : $goods_img[0];
            $data[$k]['goods_img'] = $goods_img;
        }
        return $data;
    }

    /**
     * @param $user_id
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showCollectionShop($user_id, $page = 1, $pre = 15, array $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->sortFriend, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $user = new UserData();
        $where = " a.user_id={$user_id} and a.recover_status =1";
        $data = $user->showCollectionShop($where, $page, $pre, $sort);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data,
                'total' => Common::total($where, "drh_user_attention_shop a")
            ]
        ]);
    }

    public function showUserGoodsBargain($user_id, $page = 1, $pre = 5,
                                         array $sort = ['create_time' => 'desc'], $type = 0)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->sortFriend, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $user = new UserData();
        $where = " a.user_id={$user_id} and a.bargain_num ";
        if ($type == 1) {
            $where .= " and bargain_num >0 ";
        }
        $data = $user->showUserGoodsBargain($where, $page, $pre, $sort);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data,
                'total' => Common::total($where, "drh_user_goods_bargain a")
            ]
        ]);
    }

    public function delGoodsOrder($user_id, $order_num)
    {
        $res = Common::getTableValue('drh_goods_order', ['pay_status', 'goods_status'], ['order_num', 'user_id'], [$order_num, $user_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '不存在该订单']);
        }

        if ($res['pay_status'] >= 2 && $res['goods_status'] <= 1) {
            return json(['code' => $this->f_code, 'msg' => '订单正在进行 无法删除!']);
        }
        $user = new UserData();
        $res = $user->delGoodsOrder($user_id, $order_num);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '订单删除成功']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '网络连接错误 请稍后再试!']);
        }
    }

    /**
     * 用户删除砍价商品
     * @param $user_id
     * @param $bargain_id
     * @param $goods_id
     * @return \think\response\Json
     */
    public function delUserGoodsBargain($user_id, $bargain_id, $goods_id)
    {
        $res = Common::getTableValue('drh_user_goods_bargain',
            ['id'], ['id', 'user_id','goods_id'], [$bargain_id, $user_id,$goods_id]);
        if (empty($res)) {
            return json(['code' => $this->f_code, 'msg' => '不存在该砍价商品']);
        }
        $user = new UserData();
        $user->delUserGoodsBargain($user_id, $bargain_id, $goods_id);
        return json(['code'=>$this->t_code,'msg'=>'删除成功']);
    }

}